import random
from . import settings
from qcloudsms_py import SmsSingleSender
from utils.logging import logger

ssender = SmsSingleSender(settings.APP_ID, settings.APP_KEY)


def send_msg(mobile, code, exp_time):
    try:
        response = ssender.send_with_param(
            86,
            mobile,
            settings.TEMPLATE_ID,
            params=(code, exp_time),
            sign=settings.SMS_SIGN,
            extend='',
            ext=''
        )
        if response and response.get('result') == 0:
            return True
        msg = response.get('result')
    except Exception as msg:
        pass

    logger.error('短信发送失败: %s' % msg)
    return False


def get_code():
    code = ''
    for i in range(4):
        code += str(random.randint(0, 9))

    return code
